/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package project.jsf.beans;

import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FacesException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import project.dto.NewFeedDTO;
import project.entities.NewFeedEntity;
import project.facades.interfaces.NewFeedManager;
import project.web.services.factories.NewFeedFactory;

/**
 *
 * @author armdev
 */
@ManagedBean(name = "NewFeedBean")
@ViewScoped
public class NewFeedBean implements Serializable {

    private FacesContext context;
    private ExternalContext ex;
    private NewFeedManager newFeedManager;
    private NewFeedEntity newFeedEntity;
    private String inputUrl = null;

    

    /** Creates a new instance of UserAdminBean */
    public NewFeedBean() {
        context = FacesContext.getCurrentInstance();
        ex = context.getExternalContext();
        newFeedManager = NewFeedFactory.getInstance();
        newFeedEntity = new NewFeedEntity();
    }

    public void createNewFeed() {
        try {
            if (inputUrl.trim() != null) {
                Document doc = Jsoup.connect(inputUrl).get();
                String title = doc.title();




                Elements cnt = doc.getElementsByClass("content");


                Elements links = doc.select("a[href]");
                Elements media = doc.select("[src]");
                //Elements jpg = doc.select("img[src$=.jpg]");
                Elements jpg = doc.select("[src]");
                Elements imports = doc.select("link[href]");
                Elements titles = doc.select("title");
                Element content = doc.getElementById("newsbysubjcont");
                Element content1 = doc.select("content").first();
                //Tag ddd = doc.tagName("meta");

//                 for (int i = 0; i < ddd.size(); i++) {
//                    System.out.println("______Cont__________________");
//                    System.out.println(ddd.get(i).text());
//                    System.out.println("__________Cont end______________");
//                }

                // print("\nMedia: (%d)", jpg.size());
                for (Element src : jpg) {
                    if (src.tagName().equals("img")) {
                        print(" * %s: <%s> %sx%s (%s)",
                                src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"),
                                trim(src.attr("alt"), 20));
                        if (src.attr("abs:src") != null) {
                            newFeedEntity.setMedia(src.attr("abs:src"));
                        }
                    } else {
                        print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
                    }
                }

//                print("\nImports: (%d)", imports.size());
//                for (Element link : imports) {
//                    print(" * %s <%s> (%s)", link.tagName(), link.attr("abs:href"), link.attr("rel"));
//                }

//                print("\nLinks: (%d)", links.size());
//                for (Element link : links) {
//                    print(" * a: <%s>  (%s)", link.attr("abs:href"), trim(link.text(), 35));
//                }

//                print("\nTitles: (%d)", titles.size());
//
//                for (Element link : titles) {
//                    if(link.text() != null){
//                        newFeedEntity.setSubject(link.text());
//                    }
//                    print(" * a: <%s>  (%s)", link.attr("abs:title"), trim(link.text(), 35));
//                }
//                print("\ncontent: (%d)", content.size());
//                for (Element link : content) {
//                    if(link.text() != null && link.equals(doc)){
//                        newFeedEntity.setContent(link.text());
//                    }
//                    print(" * a: <%s>  (%s)", link.attr("abs:p"), trim(link.text(), 800));
//                }

//
//                for (Element link1 : cnt) {
//                   for (Element link : content){
//                    if(link.text() != null && link.equals(doc)){
//                        newFeedEntity.setContent(link.text());
//                    }
//                    print(" * a: <%s>  (%s)", link.attr("abs:p"), trim(link.text(), 800));
//                     }
//                }                    

                if (title != null) {
                    newFeedEntity.setSubject(title);
                } else {
                    for (Element link : titles) {
                        if (link.text() != null) {
                            newFeedEntity.setSubject(link.text());
                        }
                        //  print(" * a: <%s>  (%s)", link.attr("abs:title"), trim(link.text(), 35));
                    }
                }



//                Elements el1 = doc.getElementsByAttribute("content");
//                for (int i = 0; i < el1.size(); i++) {
//                    System.out.println("________________________");
//                    System.out.println(el1.get(i).text());
//                    System.out.println("________________________");
//                }



                //Elements el = doc.getElementsMatchingText(newFeedEntity.getSubject()); vat chi

                String desc = doc.select("meta[name=description]").first().attr("content");
//                Elements meta = doc.select("meta[name=description]");
//
//                if (meta.size() > 0) {
//                    for (int i = 0; i < meta.size(); i++) {
//                        System.out.println();
//                        System.out.println("Meta list " + meta.get(i).text());
//                    }
//                }

                System.out.println("Description  " + desc);

                if (desc != null) {
                    // String el = doc.getElementsContainingText(desc.trim()).first().attr("p");
                    // newFeedEntity.setContent(el);
                    Elements el = doc.getElementsContainingOwnText(desc);
                    Elements el1 = doc.getElementsContainingOwnText(desc);
                    Elements el2 = doc.getElementsMatchingOwnText(desc);
                    Elements el3 = doc.getElementsMatchingText(desc);

                    //System.out.println("El size " + el.size());
                    System.out.println("El 1 size " + el1.size());
                    System.out.println("El 2  size " + el2.size());
                    System.out.println("El  3 size " + el3.size());


                if (el.size() > 0) {
                    for (int i = 0; i < el.size(); i++) {
                        newFeedEntity.setContent(el.get(i).text());
                    }
                }
            }
               

             //   newFeedEntity.setContent(content.text());

//                   if(cnt.text().contains(title.substring(0,3)) || cnt.text().contains(title.substring(0,4))||
//                           cnt.text().contains(title.substring(0,5))){
//                   newFeedEntity.setContent(cnt.text());
//                   }

                newFeedEntity.setUrl(inputUrl);
                newFeedEntity.setDatePulished(new Date(System.currentTimeMillis()));
                newFeedManager.create(newFeedEntity);
            }
        } catch (IOException ex) {
            Logger.getLogger(NewFeedBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private static void print(String msg, Object... args) {
        System.out.println(String.format(msg, args));
    }

    private static String trim(String s, int width) {
        if (s.length() > width) {
            return s.substring(0, width - 1) + ".";
        } else {
            return s;
        }
    }

    public String getInputUrl() {
        return inputUrl;
    }

    public void setInputUrl(String inputUrl) {
        this.inputUrl = inputUrl;
    }

    public List<NewFeedDTO> getNewFeedList() {
        return newFeedManager.getFeedList(0, 1000);
    }

    private static void redirect(FacesContext facesContext, String url) {
        try {
            facesContext.getExternalContext().redirect(url);
        } catch (IOException e) {
            throw new FacesException("Cannot redirect to " + url + " due to IO exception.", e);
        }
    }
}
